<template>
  <div>
    <el-card>
      <div>
        <div>
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-row>
              <el-col :span="4">
                <el-form-item label="工作单位" prop="companyNameLike">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.companyNameLike"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="姓名" prop="nameLike">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.nameLike"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="职称" prop="ext5Like">
                  <el-input
                    class="search-input"
                    v-model.trim="formInline.ext5Like"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="专家类型" prop="isInOut">
                  <el-select
                    class="search-input"
                    clearable
                    v-model="formInline.isInOut"
                  >
                    <el-option
                      v-for="item in typeList"
                      :label="item.dicValue"
                      :key="item.dicCode"
                      :value="item.dicCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="登记时间" prop="updateTime">
                  <el-date-picker
                    style="width: 90%"
                    v-model.trim="formInline.updateTime"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item class="right-position">
                  <el-button type="primary" @click="handleSearch">
                    搜索
                  </el-button>
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div style="margin-bottom: 8px">
          <el-button
            type="primary"
            @click="handleAdd"
            class="add-option"
            v-auth="`/expert/manage--add`"
            >添加</el-button
          >
          <el-button
            type="primary"
            @click="exportExcel"
            class="add-option"
            v-auth="`/expert/manage--export`"
            >导出</el-button
          >
          <importExcel
            fileName="内部专家人员导入模版.xlsx"
            :actionUrl="importUrlInner"
            name="uploadFile"
            title="导入内部专家"
            auth="/expert/manage--import-inside"
            @onSuccess="handleSearch"
          />
          <importExcel
            fileName="外部专家人员导入模版.xlsx"
            :actionUrl="importUrlOuter"
            name="uploadFile"
            title="导入外部专家"
            auth="/expert/manage--import-outside"
            @onSuccess="handleSearch"
          />
        </div>
        <el-tabs v-model="activeName" @tab-click="changeTab" :lazy="true">
          <el-tab-pane label="全部组别专家" name=""></el-tab-pane>
          <el-tab-pane
            v-for="(item, index) in ext1s"
            :key="index"
            :label="item.label"
            :name="item.key"
          >
          </el-tab-pane>
        </el-tabs>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column
              prop="companyName"
              label="工作单位"
            ></el-table-column>
            <el-table-column prop="position" label="职务"></el-table-column>
            <el-table-column prop="ext5" label="职称"></el-table-column>
            <el-table-column
              prop="studyMajor"
              label="所学专业"
            ></el-table-column>
            <el-table-column
              prop="workMajor"
              label="现从事专业"
            ></el-table-column>
            <el-table-column prop="ext1" label="专家组别"></el-table-column>
            <el-table-column
              prop="inOutName"
              label="专家类型"
            ></el-table-column>
            <el-table-column prop="lastUpdateTime" label="登记时间">
              <template v-slot="scope">
                {{ scope.row.lastUpdateTime ? scope.row.lastUpdateTime.split(" ")[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="text"
                  @click="handleCheckDetail(row)"
                  v-auth="`/expert/manage--look`"
                  >查看</el-button
                >
                <el-button
                  type="text"
                  @click="handleEdit(row, true)"
                  v-auth="`/expert/manage--edit`"
                  >编辑</el-button
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button type="text" v-auth="`/expert/manage--delete`"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      :title="
        mode === 'add' ? '添加专家' : mode === 'edit' ? '编辑专家' : '查看专家'
      "
      v-model="dialogFormVisible"
      destroy-on-close
      width="45vw"
    >
      <expert-detail
        :mode="mode"
        :companyInfo="companyInfo"
        @emitSubmit="onEmitSubmit"
      />
    </el-dialog>
    <el-dialog
      v-model="detailVisible"
      destroy-on-close
      title="登记历史记录"
      width="80%"
    >
      <check-detail :companyInfo="companyInfo" />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import { postDictList } from "/@/api/common";
import { getExpertStaffList, postExpertStaffDelete } from "/@/api/expert";
import NotifMessage from "/@/utils/message/notification";
// import RePagination from "/@/components/RePagination/index.vue";
import axios from "axios";
import { cloneDeep } from "lodash-es";
import moment from "moment";
import ExpertDetail from "./components/ExpertDetail.vue";
import CheckDetail from "./components/checkDetail.vue";
import importExcel from "/@/components/importExcel/index.vue";
import { storageLocal } from "/@/utils/storage";
export default defineComponent({
  name: "UserManage",
  components: {
    ExpertDetail,
    importExcel,
    CheckDetail
    // RePagination
  },
  setup() {
    const ext1s = ref([
      { key: "风味", label: "风味" },
      { key: "可持续发展", label: "可持续发展" },
      { key: "智能与数字化", label: "智能与数字化" },
      { key: "食品包装", label: "食品包装" },
      { key: "酿造技术及原料", label: "酿造技术及原料" },
      { key: "菌种酵母", label: "菌种酵母" },
      { key: "酒文化", label: "酒文化" },
      { key: "物流技术", label: "物流技术" }
      // { key: "经济", label: "经济" }
    ]);
    const baseUrl = import.meta.env.VITE_BASE_URL;
    const importUrlInner = ref(
      import.meta.env.VITE_BASE_URL + "/rdms-admin/expertStaff/importInner"
    );
    const importUrlOuter = ref(
      import.meta.env.VITE_BASE_URL + "/rdms-admin/expertStaff/importOut"
    );
    const formRef = ref<HTMLFormElement | null>(null) as any;
    let loading = ref<boolean>(false);
    let dialogFormVisible = ref<boolean>(false);
    let total = ref<number>(0);
    let formInline = reactive<any>({
      principalCompanyCodeIn: "",
      nameLike: "",
      userNameLike: "",
      companyNameLike: "",
      ext5Like: "",
      isInOut: "",
      ext1: "",
      positionLike: "",
      updateTime: "",
      pageSize: 10,
      pageNum: 1
    });
    let mode = ref<string>("add");
    let state = reactive({
      activeName: "",
      tableData: [],
      companyInfo: {},
      detailVisible: false // 查看详情弹窗状态
    });

    let typeList = ref([]);

    // 请求公司列表表格数据
    async function getTableData(obj: object = {}) {
      // 真实请求待添加
      loading.value = true;
      try {
        let copyParams = cloneDeep(obj);
        if (copyParams.principalCompanyCodeIn === "") {
          copyParams.principalCompanyCodeIn = [];
        } else {
          copyParams.principalCompanyCodeIn =
            copyParams.principalCompanyCodeIn.split(",");
        }

        const { code, data } = await getExpertStaffList(copyParams);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }

    // 查看详情弹窗状态
    const handleCheckDetail = row => {
      state.detailVisible = true;
      state.companyInfo = row;
    };
    // 打开添加人员弹窗
    const handleAdd = (): void => {
      mode.value = "add";
      dialogFormVisible.value = true;
    };

    // 操作
    const onEmitSubmit = (isSubmit: boolean) => {
      dialogFormVisible.value = false;
      if (isSubmit) {
        handleSearch();
      }
    };

    // 清除表单，重置
    const handleReset = () => {
      formRef.value.resetFields();
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      const params = cloneDeep(formInline);
      if (formInline.updateTime) {
        params.updateTime = moment(formInline.updateTime).format("YYYY-MM-DD");
      } else {
        params.updateTime = "";
      }
      getTableData(params);
    };

    // 删除记录
    const handleDelete = async item => {
      try {
        const { code, message } = await postExpertStaffDelete({ id: item.id });
        if (code === 200) {
          NotifMessage.success(`${message}`);
          handleSearch();
        } else {
          NotifMessage.error(`${message}`);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleEdit = (row, isEdit) => {
      dialogFormVisible.value = true;
      mode.value = isEdit ? "edit" : "view";
      state.companyInfo = row;
    };

    // 项目阶段
    const initTypeList = async () => {
      try {
        const params = {
          dicType: "rd_in_out_type"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          typeList.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 导出
    const exportExcel = async () => {
      let downloadUrl = `/rdms-admin/expertStaff/export`;
      let authorization = "";
      if (storageLocal.getItem("rdms-info")) {
        authorization = storageLocal.getItem("rdms-info")?.accessToken;
      }
      if (import.meta.env.MODE === "production") {
        downloadUrl = `${baseUrl}/rdms-admin/expertStaff/export`;
      }
      const param = Object.assign({}, formInline, { pageSize: 0, pageNum: 1 });
      if (param.principalCompanyCodeIn === "") {
        param.principalCompanyCodeIn = [];
      } else {
        param.principalCompanyCodeIn = param.principalCompanyCodeIn.split(",");
      }
      axios({
        method: "post",
        url: downloadUrl,
        data: param,
        responseType: "blob",
        headers: {
          Authorization: authorization
        }
      }).then(res => {
        const data = res.data;
        // @ts-ignore
        const url = window.URL.createObjectURL(new Blob([data]));
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
        a.setAttribute("download", `专家列表.xlsx`);
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
      });
    };

    const changeTab = item => {
      state.activeName = item.props.name;
      formInline.ext1 = item.props.name;
      handleSearch();
    };

    initTypeList();

    // 请求数据
    getTableData(formInline);
    return {
      changeTab,
      ext1s,
      importUrlInner,
      importUrlOuter,
      loading,
      dialogFormVisible,
      formInline,
      formRef,
      mode,
      total,
      typeList,
      ...toRefs(state),
      handleAdd,
      handleReset,
      handleSearch,
      handleDelete,
      handleEdit,
      onEmitSubmit,
      exportExcel,
      handleCheckDetail
    };
  }
});
</script>
